<template>
    <view class="container">
        <!-- 使用状态 -->
        <view class="status-card">
            <view class="status-icon">
                <image src="/static/images/device/using.png" mode="aspectFit"></image>
            </view>
            <view class="status-text">使用中</view>
            <view class="time-info">
                <text>已使用时长</text>
                <view class="time">{{ formatDuration }}</view>
            </view>
        </view>

        <!-- 设备信息 -->
        <view class="info-card">
            <view class="info-item">
                <text class="label">设备编号</text>
                <text class="value">{{ deviceInfo.deviceNo }}</text>
            </view>
            <view class="info-item">
                <text class="label">所在位置</text>
                <text class="value">{{ deviceInfo.hospitalName }} {{ deviceInfo.departmentName }}</text>
            </view>
            <view class="info-item">
                <text class="label">床位号</text>
                <text class="value">{{ deviceInfo.bedNo }}</text>
            </view>
            <view class="info-item">
                <text class="label">开始时间</text>
                <text class="value">{{ formatTime(deviceInfo.startTime) }}</text>
            </view>
        </view>

        <!-- 费用信息 -->
        <view class="price-card">
            <view class="price-row">
                <text>当前费用</text>
                <text class="price">￥{{ currentAmount }}</text>
            </view>
            <view class="price-tip">每小时{{ deviceInfo.price }}元，按分钟计费</view>
        </view>

        <!-- 底部操作栏 -->
        <view class="bottom-bar">
            <button class="action-btn" @tap="showFeedback">
                <image src="/static/images/device/feedback.png"></image>
                <text>故障反馈</text>
            </button>
            <button class="action-btn" @tap="callService">
                <image src="/static/images/device/service.png"></image>
                <text>联系客服</text>
            </button>
            <button class="end-btn" @tap="handleEndUse">结束使用</button>
        </view>

        <!-- 故障反馈弹窗 -->
        <uni-popup ref="feedbackPopup" type="bottom">
            <view class="feedback-popup">
                <view class="popup-header">
                    <text>故障反馈</text>
                    <view class="close-btn" @tap="closeFeedback">×</view>
                </view>
                <view class="feedback-content">
                    <view class="fault-types">
                        <view 
                            v-for="(item, index) in faultTypes" 
                            :key="index"
                            class="fault-item"
                            :class="{ active: selectedFault === index }"
                            @tap="selectFault(index)"
                        >
                            {{ item }}
                        </view>
                    </view>
                    <textarea 
                        class="fault-desc"
                        v-model="faultDesc"
                        placeholder="请描述具体问题（选填）"
                        maxlength="200"
                    ></textarea>
                    <view class="upload-images">
                        <view 
                            class="image-item" 
                            v-for="(item, index) in uploadImages" 
                            :key="index"
                        >
                            <image :src="item" mode="aspectFill"></image>
                            <view class="delete-btn" @tap="deleteImage(index)">×</view>
                        </view>
                        <view class="upload-btn" @tap="chooseImage" v-if="uploadImages.length < 3">
                            <image src="/static/images/device/upload.png"></image>
                            <text>上传图片</text>
                        </view>
                    </view>
                </view>
                <view class="popup-footer">
                    <button class="submit-btn" @tap="submitFeedback">提交反馈</button>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import { getDeviceDetail, endUse } from '@/api/device'
import { submitFault } from '@/api/feedback'

export default {
    data() {
        return {
            deviceInfo: {},
            startTime: null,
            timer: null,
            duration: 0,
            faultTypes: ['无法开锁', '无法关锁', '设备损坏', '其他问题'],
            selectedFault: -1,
            faultDesc: '',
            uploadImages: []
        }
    },
    computed: {
        formatDuration() {
            const hours = Math.floor(this.duration / 3600)
            const minutes = Math.floor((this.duration % 3600) / 60)
            return `${hours}小时${minutes}分钟`
        },
        currentAmount() {
            const hours = this.duration / 3600
            return (hours * this.deviceInfo.price).toFixed(2)
        }
    },
    onLoad(options) {
        this.deviceNo = options.code
        this.getDeviceInfo()
    },
    onUnload() {
        this.clearTimer()
    },
    methods: {
        async getDeviceInfo() {
            try {
                const res = await getDeviceDetail(this.deviceNo)
                this.deviceInfo = res
                this.startTime = new Date(res.startTime)
                this.startTimer()
            } catch (error) {
                uni.showToast({
                    title: '获取设备信息失败',
                    icon: 'none'
                })
            }
        },
        
        startTimer() {
            this.clearTimer()
            this.timer = setInterval(() => {
                const now = new Date()
                this.duration = Math.floor((now - this.startTime) / 1000)
            }, 1000)
        },
        
        clearTimer() {
            if (this.timer) {
                clearInterval(this.timer)
                this.timer = null
            }
        },
        
        formatTime(time) {
            return time.replace('T', ' ').substring(0, 16)
        },
        
        // 结束使用
        async handleEndUse() {
            try {
                await uni.showModal({
                    title: '提示',
                    content: '确认结束使用吗？'
                })
                
                await endUse(this.deviceNo)
                uni.showToast({
                    title: '操作成功',
                    icon: 'success'
                })
                
                setTimeout(() => {
                    uni.redirectTo({
                        url: '/pages/order/index'
                    })
                }, 1500)
            } catch (error) {
                if (error.errMsg !== 'showModal:fail cancel') {
                    uni.showToast({
                        title: error.message || '操作失败',
                        icon: 'none'
                    })
                }
            }
        },
        
        // 故障反馈相关方法
        showFeedback() {
            this.$refs.feedbackPopup.open()
        },
        
        closeFeedback() {
            this.$refs.feedbackPopup.close()
            this.resetFeedback()
        },
        
        selectFault(index) {
            this.selectedFault = index
        },
        
        async chooseImage() {
            try {
                const res = await uni.chooseImage({
                    count: 3 - this.uploadImages.length,
                    sizeType: ['compressed']
                })
                this.uploadImages = [...this.uploadImages, ...res.tempFilePaths]
            } catch (error) {
                console.log('选择图片失败', error)
            }
        },
        
        deleteImage(index) {
            this.uploadImages.splice(index, 1)
        },
        
        resetFeedback() {
            this.selectedFault = -1
            this.faultDesc = ''
            this.uploadImages = []
        },
        
        async submitFeedback() {
            if (this.selectedFault === -1) {
                uni.showToast({
                    title: '请选择故障类型',
                    icon: 'none'
                })
                return
            }
            
            try {
                const uploadedImages = await this.uploadImages()
                await submitFault({
                    deviceNo: this.deviceNo,
                    faultType: this.selectedFault,
                    faultDesc: this.faultDesc,
                    images: uploadedImages
                })
                
                uni.showToast({
                    title: '提交成功',
                    icon: 'success'
                })
                
                this.closeFeedback()
            } catch (error) {
                uni.showToast({
                    title: error.message || '提交失败',
                    icon: 'none'
                })
            }
        },
        
        // 上传图片
        async uploadImages() {
            if (this.uploadImages.length === 0) return []
            
            const promises = this.uploadImages.map(path => {
                return new Promise((resolve, reject) => {
                    uni.uploadFile({
                        url: '/api/upload',
                        filePath: path,
                        name: 'file',
                        success: res => {
                            const data = JSON.parse(res.data)
                            resolve(data.url)
                        },
                        fail: reject
                    })
                })
            })
            
            return Promise.all(promises)
        },
        
        callService() {
            uni.makePhoneCall({
                phoneNumber: '400-888-8888'
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.container {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: 120rpx;
    
    .status-card {
        background-color: #07c160;
        padding: 60rpx 30rpx;
        text-align: center;
        color: #fff;
        
        .status-icon {
            width: 120rpx;
            height: 120rpx;
            margin: 0 auto 20rpx;
            
            image {
                width: 100%;
                height: 100%;
            }
        }
        
        .status-text {
            font-size: 36rpx;
            font-weight: bold;
            margin-bottom: 30rpx;
        }
        
        .time-info {
            text {
                font-size: 28rpx;
                opacity: 0.9;
            }
            
            .time {
                font-size: 48rpx;
                font-weight: bold;
                margin-top: 10rpx;
            }
        }
    }
    
    .info-card, .price-card {
        margin: 20rpx;
        background-color: #fff;
        border-radius: 12rpx;
        padding: 30rpx;
    }
    
    .info-card {
        .info-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20rpx;
            
            &:last-child {
                margin-bottom: 0;
            }
            
            .label {
                color: #666;
                font-size: 28rpx;
            }
            
            .value {
                color: #333;
                font-size: 28rpx;
            }
        }
    }
    
    .price-card {
        .price-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10rpx;
            
            text {
                font-size: 28rpx;
                color: #666;
            }
            
            .price {
                font-size: 40rpx;
                color: #f44336;
                font-weight: bold;
            }
        }
        
        .price-tip {
            font-size: 24rpx;
            color: #999;
        }
    }
    
    .bottom-bar {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        height: 100rpx;
        background-color: #fff;
        display: flex;
        align-items: center;
        padding: 0 30rpx;
        box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
        
        .action-btn {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: none;
            margin: 0;
            padding: 0;
            width: 120rpx;
            
            &::after {
                display: none;
            }
            
            image {
                width: 48rpx;
                height: 48rpx;
                margin-bottom: 6rpx;
            }
            
            text {
                font-size: 24rpx;
                color: #666;
            }
        }
        
        .end-btn {
            flex: 1;
            height: 72rpx;
            line-height: 72rpx;
            background: #07c160;
            color: #fff;
            font-size: 28rpx;
            border-radius: 36rpx;
            margin-left: 30rpx;
        }
    }
}

.feedback-popup {
    background-color: #fff;
    border-radius: 24rpx 24rpx 0 0;
    
    .popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 30rpx;
        border-bottom: 1rpx solid #eee;
        
        text {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
        }
        
        .close-btn {
            font-size: 48rpx;
            color: #999;
            padding: 0 20rpx;
        }
    }
    
    .feedback-content {
        padding: 30rpx;
        
        .fault-types {
            display: flex;
            flex-wrap: wrap;
            gap: 20rpx;
            margin-bottom: 30rpx;
            
            .fault-item {
                padding: 20rpx 40rpx;
                background: #f5f5f5;
                border-radius: 30rpx;
                font-size: 28rpx;
                color: #666;
                
                &.active {
                    background: #07c160;
                    color: #fff;
                }
            }
        }
        
        .fault-desc {
            width: 100%;
            height: 200rpx;
            background: #f5f5f5;
            border-radius: 12rpx;
            padding: 20rpx;
            font-size: 28rpx;
            margin-bottom: 30rpx;
        }
        
        .upload-images {
            display: flex;
            flex-wrap: wrap;
            gap: 20rpx;
            
            .image-item, .upload-btn {
                width: 200rpx;
                height: 200rpx;
                border-radius: 12rpx;
                overflow: hidden;
            }
            
            .image-item {
                position: relative;
                
                image {
                    width: 100%;
                    height: 100%;
                }
                
                .delete-btn {
                    position: absolute;
                    right: 10rpx;
                    top: 10rpx;
                    width: 40rpx;
                    height: 40rpx;
                    background: rgba(0,0,0,0.5);
                    border-radius: 20rpx;
                    color: #fff;
                    font-size: 32rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
            }
            
            .upload-btn {
                background: #f5f5f5;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                
                image {
                    width: 48rpx;
                    height: 48rpx;
                    margin-bottom: 10rpx;
                }
                
                text {
                    font-size: 24rpx;
                    color: #999;
                }
            }
        }
    }
    
    .popup-footer {
        padding: 30rpx;
        
        .submit-btn {
            width: 100%;
            height: 88rpx;
            line-height: 88rpx;
            background: #07c160;
            color: #fff;
            font-size: 32rpx;
            border-radius: 44rpx;
        }
    }
}
</style> 